using System;
using UnityEngine;

namespace Yukisky.IdentifyUser
{

    public class IdentifyResult
    {
        public bool Success;
        public string Birthday;
        /// <summary>
        /// BUS AUTH 验证相关
        /// BUS COLL 行为上报相关
        /// SYS 系统异常
        /// 
        /// </summary>
        public string ErrorMsg;
        public bool Flush = false;

        public override string ToString()
        {
            return $"结果:${Success} , 生日:{Birthday} ,{(string.IsNullOrEmpty(ErrorMsg) ? "" : ErrorMsg)}";
        }
    }
    
    
    /// <summary>
    /// 实名认证管理
    /// 有效性验证和记录
    /// </summary>
    public partial class IdentifyMgr
    {

        static IdentifyMgr _mgr;

        public static IdentifyMgr GetInstance()
        {
            return _mgr ?? (_mgr = new IdentifyMgr());
        }

        public void SetHost(string url)
        {
            _service.SetHost(url);
        }

        private static IBadWordServices BadWordServices;

        public static IBadWordServices GetBadWordServices()
        {
            if (BadWordServices == null)
            {
                BadWordServices = new DefaultBadWordServices();
            }
            return BadWordServices;
        }

        private static ITimeServices TimeServices;
        public static ITimeServices GetTimeServices()
        {
            if (TimeServices == null)
            {
                TimeServices = new DefaultTimeServices();
            }
            return TimeServices;
        }

        private static IDBServices DBServices;
        public static IDBServices GetDBServices()
        {
            if (DBServices == null)
            {
                DBServices = new DefaultDBServices();
            }
            return DBServices;
        }
        
        private static string TAG = "防沉迷";
        public static void Log(string str)
        {
            Debug.Log($"[{TAG}]{str}");
        }
        
        public static void LogError(string str)
        {
            Debug.LogError($"[{TAG}]{str}");
        }
        
        public static void Init()
        {
            Init("IdentifyUserSettings");
        }
        
        public static void Init(string identifyUserSettingsName)
        {
            IdentifyUserSettings settings = Resources.Load<IdentifyUserSettings>(identifyUserSettingsName);
            if (settings == null)
            {
                LogError("加载防沉迷配置信息失败,找不到IdentifyUserSettings文件");
                return;
            }
            Init(settings);
        }

        private static IdentifyUserSettings _settings;
        public static void Init(IdentifyUserSettings settings)
        {
            _settings = settings;
        }
        
        private static IUserInfo _userInfo;
        public static IUserInfo GetUserInfo()
        {
            if (_userInfo == null)
            {
                LogError("没有设置IUserInfo");
            }
            return _userInfo;
        }
        
        public static void InitServices(IUserInfo userInfo,IBadWordServices badWord = null, ITimeServices timeServices = null, IDBServices dbServices = null)
        {
            BadWordServices = badWord;
            TimeServices = timeServices;
            DBServices = dbServices;
            _userInfo = userInfo;
        }

        private const string BIRTHDAY_KEY = "identify_birthday";

        private IIdentifyService _service;

        private int _age = 0; //当前的年龄
        private string _birthday = String.Empty;
        private bool _verified = false; //是否认证过


        public int Age()
        {
            return _age;
        }

        public string Birthday
        {
            get => _birthday;
        }

        public IdentifyMgr()
        {
            if (_settings.Offical)
            {
                Request.Init(_settings,GetUserInfo());
                _service = new Request();
            }
            else
            {
                _service = new DummyVerify();
            }
            _birthday = GetDBServices().GetString(BIRTHDAY_KEY,String.Empty);
            if (!string.IsNullOrEmpty(_birthday))
            {
                _verified = true;
                IsMajority(true);
            }
        }
        
        /// <summary>
        /// 实名认证,并记录认证信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <param name="complete"></param>
        public void Verify(string name,string number,Action<IdentifyResult> complete)
        {
            _service.Verify(name,number,(result =>
            {
                if (result.Success)
                {
                    //判断年龄
                    var birthDays = result.Birthday.Split('.');
                    var time = Utils.GetTime();
                    int age = Utils.CalculateAge(time.Year, time.Month, time.Day,
                        int.Parse(birthDays[0]),
                        int.Parse(birthDays[1]),
                        int.Parse(birthDays[2]));
                    if (age < 0)
                    {
                        result.ErrorMsg = "2";
                        complete(result);
                    }
                    else
                    {
                        Save(result.Birthday,age);
                        complete(result);
                    }
                }
                else
                {
                    complete(result);
                }
            }));
        }

        public bool HasVerified()
        {
            return _verified;
        }
        
        /// <summary>
        /// 判断是否成年
        /// </summary>
        /// <param name="update">判断之前是否更新</param>
        /// <returns></returns>
        public bool IsMajority(bool update)
        {
            if (update)
            {
                var time = Utils.GetTime();
                var birthDays = _birthday.Split('.');
                _age = Utils.CalculateAge(time.Year, time.Month, time.Day,
                    int.Parse(birthDays[0]),
                    int.Parse(birthDays[1]),
                    int.Parse(birthDays[2]));
            }
            return _age >= 18;
        }

        partial void TestChangeAge(int newAge);

        /// <summary>
        /// 清空认证信息
        /// </summary>
        public void Clear()
        {
            GetDBServices().Remove(BIRTHDAY_KEY);
            GetDBServices().PersistData();
            _verified = false;
            _birthday = String.Empty;
            _age = 0;
            _service.Clear();
        }

        private void Save(string birthday,int age , bool flush = true)
        {
            _verified = true;
            _age = age;
            _birthday = birthday;
            GetDBServices().SetString(BIRTHDAY_KEY,birthday,flush);
        }

        //tick 心跳包
        public void Update()
        {
            _service.Update();
        }
    }
}